<template>
  <div class="unit-management">
    <div class="page-header">
      <div class="header-left">
        <h2>单位管理</h2>
      </div>
      <div class="header-right">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedUnits.length === 0">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>新建单位
        </el-button>
        <el-button type="success" @click="showBulkImportDialog">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-panel">
      <el-form :inline="true" :model="searchForm" class="search-form" @keyup.enter="handleSearch">
        <el-form-item label="单位名称">
          <el-input v-model="searchForm.name" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择类型"
            clearable
            style="width: 150px"
          >
            <el-option label="重量单位" value="重量单位" />
            <el-option label="长度单位" value="长度单位" />
            <el-option label="体积单位" value="体积单位" />
            <el-option label="数量单位" value="数量单位" />
            <el-option label="其他单位" value="其他单位" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 单位列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading.units"
        :data="units"
        border
        style="width: 100%"
        @expand-change="handleExpandChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="conversion-rules-container">
              <div class="rules-header">
                <h4>转换规则</h4>
                <el-button type="primary" size="small" @click="showAddRuleDialog(row)">
                  <el-icon><Plus /></el-icon>添加规则
                </el-button>
              </div>
              
              <el-table 
                :data="row.conversions || []" 
                border 
                size="small" 
                class="conversion-rules-table"
                v-if="row.conversions && row.conversions.length > 0"
              >
                <el-table-column prop="source_unit" label="源单位" width="100" />
                <el-table-column prop="target_unit" label="目标单位" width="100" />
                <el-table-column prop="conversion_formula" label="转换公式" width="180">
                  <template #default="{ row: rule }">
                    <div class="formula-container">
                      <span class="formula-text">{{ rule.conversion_formula }}</span>
                      <el-tooltip 
                        placement="top" 
                        effect="light"
                        :content="`将${rule.source_unit}转换为${rule.target_unit}`" 
                      >
                        <el-popover
                          placement="top"
                          title="公式示例"
                          :width="200"
                          trigger="hover"
                        >
                          <template #default>
                            <div class="formula-example">
                              <div class="example-row">
                                <span>1 {{ rule.source_unit }} = {{ evaluateFormula(rule.conversion_formula, 1) }} {{ rule.target_unit }}</span>
                              </div>
                              <div class="example-row">
                                <span>5 {{ rule.source_unit }} = {{ evaluateFormula(rule.conversion_formula, 5) }} {{ rule.target_unit }}</span>
                              </div>
                              <div class="example-row">
                                <span>10 {{ rule.source_unit }} = {{ evaluateFormula(rule.conversion_formula, 10) }} {{ rule.target_unit }}</span>
                              </div>
                            </div>
                          </template>
                          <template #reference>
                            <el-button type="info" size="small" circle plain>
                              <el-icon><InfoFilled /></el-icon>
                            </el-button>
                          </template>
                        </el-popover>
                      </el-tooltip>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="130" show-overflow-tooltip />
                <el-table-column prop="created_at" label="创建时间" width="150">
                  <template #default="{ row: rule }">
                    {{ formatDate(rule.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column prop="is_active" label="状态" width="80">
                  <template #default="{ row: rule }">
                    <el-tag :type="rule.is_active ? 'success' : 'info'">
                      {{ rule.is_active ? '启用' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="{ row: rule }">
                    <el-button-group class="operation-buttons">
                      <el-button type="primary" size="small" @click="showEditRuleDialog(row, rule)">
                        <el-icon><Edit /></el-icon>编辑
                      </el-button>
                      <el-button type="danger" size="small" @click="handleDeleteRule(rule)">
                        <el-icon><Delete /></el-icon>删除
                      </el-button>
                    </el-button-group>
                  </template>
                </el-table-column>
              </el-table>
              
              <el-empty v-else description="暂无转换规则" />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="单位名称" min-width="120" />
        <el-table-column prop="type" label="单位类型" width="120" />
        <el-table-column label="转换规则数" width="120">
          <template #default="{ row }">
            <el-tag :type="(row.conversions?.length || 0) > 0 ? 'success' : 'info'">
              {{ row.conversions?.length || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button-group class="operation-buttons">
              <el-button type="primary" @click="showEditDialog(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                :type="row.is_active ? 'warning' : 'success'" 
                @click="handleToggleStatus(row)"
              >
                <el-icon><SwitchButton /></el-icon>
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑单位对话框 -->
    <el-dialog
      v-model="dialogs.unit"
      :title="editingUnit.id ? '编辑单位' : '新建单位'"
      width="550px"
    >
      <el-form
        ref="unitFormRef"
        :model="editingUnit"
        :rules="unitRules"
        label-width="100px"
      >
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="editingUnit.name" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位类型" prop="type">
          <el-select v-model="editingUnit.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="重量单位" value="重量单位" />
            <el-option label="长度单位" value="长度单位" />
            <el-option label="体积单位" value="体积单位" />
            <el-option label="数量单位" value="数量单位" />
            <el-option label="其他单位" value="其他单位" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="editingUnit.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.unit = false">取消</el-button>
          <el-button type="primary" :loading="loading.submit" @click="handleSubmitUnit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建/编辑转换规则对话框 -->
    <el-dialog
      v-model="dialogs.rule"
      :title="editingRule.id ? '编辑转换规则' : '添加转换规则'"
      width="550px"
    >
      <el-form
        ref="ruleFormRef"
        :model="editingRule"
        :rules="ruleRules"
        label-width="100px"
      >
        <el-form-item label="源单位" prop="source_unit">
          <el-input v-model="editingRule.source_unit" placeholder="请输入源单位" :disabled="true" />
        </el-form-item>
        <el-form-item label="目标单位" prop="target_unit">
          <el-input v-model="editingRule.target_unit" placeholder="请输入目标单位" />
        </el-form-item>
        <el-form-item label="转换公式" prop="conversion_formula">
          <el-input v-model="editingRule.conversion_formula" placeholder="请输入转换公式，如 x * 2">
            <template #prepend>
              <span>x = </span>
            </template>
          </el-input>
          <div class="form-tip">转换公式中使用变量x表示源单位的值，如：x * 2表示乘以2；x / 1000表示除以1000</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editingRule.description" 
            type="textarea" 
            :rows="2" 
            placeholder="请输入描述，例如：克转千克"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="editingRule.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.rule = false">取消</el-button>
          <el-button type="primary" :loading="loading.submitRule" @click="handleSubmitRule">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="dialogs.bulkImport"
      title="批量导入单位"
      width="600px"
    >
      <div class="bulk-import-dialog">
        <el-alert
          type="info"
          show-icon
          :closable="false"
          title="请按照JSON格式输入单位数据，每行一个单位对象"
        />
        <p class="format-example">格式示例：<code>[{"name": "千克", "type": "重量"}, {"name": "米", "type": "长度"}]</code></p>
        <el-input
          v-model="bulkImportData"
          type="textarea"
          :rows="10"
          placeholder="请输入JSON格式的单位数据"
          @input="validateBulkImportData"
        />
        <div v-if="bulkImportError" class="json-error">
          <el-alert
            type="error"
            show-icon
            :closable="false"
            :title="bulkImportError"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.bulkImport = false">取消</el-button>
          <el-button type="primary" :loading="loading.bulkImport" @click="handleBulkImport">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Edit, Delete, Search, RefreshRight, Upload, SwitchButton, InfoFilled
} from '@element-plus/icons-vue'
import { 
  getUnitList, 
  createUnitConversion, 
  updateUnitConversion, 
  deleteUnitConversion,
  deleteConversionRule,
  bulkCreateUnits,
  getUnitConversionList,
  getUnitDetail
} from '@/api/config'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  is_active: ''
})

// 状态变量
const units = ref([])
const editingUnit = ref({
  name: '',
  type: '重量单位',
  is_active: true
})
const editingRule = ref({
  source_unit: '',
  target_unit: '',
  conversion_formula: '',
  description: '',
  is_active: true
})
const currentUnit = ref(null)
const bulkImportData = ref('')
const bulkImportError = ref('')
const selectedUnits = ref([])
const expandedRowKeys = ref([])

// 加载状态
const loading = reactive({
  units: false,
  submit: false,
  submitRule: false,
  bulkImport: false
})

// 对话框显示状态
const dialogs = reactive({
  unit: false,
  rule: false,
  bulkImport: false
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const unitFormRef = ref(null)
const ruleFormRef = ref(null)

// 表单验证规则
const unitRules = {
  name: [
    { required: true, message: '请输入单位名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择单位类型', trigger: 'change' }
  ]
}

const ruleRules = {
  source_unit: [
    { required: true, message: '请输入源单位', trigger: 'blur' }
  ],
  target_unit: [
    { required: true, message: '请输入目标单位', trigger: 'blur' }
  ],
  conversion_formula: [
    { required: true, message: '请输入转换公式', trigger: 'blur' },
    { 
      pattern: /^[x\s\d+\-*/().]+$/, 
      message: '公式格式错误，只能包含x、数字和运算符', 
      trigger: 'blur' 
    }
  ]
}

// 初始化
onMounted(() => {
  fetchUnitList()
})

// 获取单位列表
const fetchUnitList = async () => {
  try {
    loading.units = true
    
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }
    
    if (searchForm.type) {
      params.type = searchForm.type
    }
    
    if (searchForm.is_active !== '') {
      params.is_active = searchForm.is_active
    }
    
    if (searchForm.name) {
      params.name = searchForm.name
    }
    
    const response = await getUnitList(params)
    
    if (response) {
      // 处理后端返回对象包含items的情况
      if (response && response.items) {
        units.value = response.items
        pagination.total = response.total || 0
      } 
      // 处理后端直接返回数组的情况（兼容旧接口）
      else if (Array.isArray(response)) {
        units.value = response
        pagination.total = response.length
      } else {
        units.value = []
        pagination.total = 0
      }
    } else {
      units.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取单位列表失败:', error)
    ElMessage.error('获取单位列表失败')
    units.value = []
    pagination.total = 0
  } finally {
    loading.units = false
  }
}

// 展开行时的处理
const handleExpandChange = async (expandedRows) => {
  expandedRowKeys.value = expandedRows;
  
  if (expandedRows.length > 0) {
    for (const rowKey of expandedRows) {
      const row = units.value.find(unit => unit.id === rowKey);
      
      if (row && (!row.conversions || row.conversions.length === 0)) {
        try {
          // 使用unit_id参数获取指定单位的转换规则
          console.log('获取单位ID的转换规则:', row.id);
          
          const response = await getUnitDetail(row.id);
          
          console.log('获取到的单位详情:', response);
          
          // 直接从单位详情中获取转换规则
          if (response && response.conversions) {
            row.conversions = response.conversions;
          } else if (response && response.id === row.id) {
            // 如果没有conversions字段，尝试使用另一个API获取
            const conversionResponse = await getUnitConversionList({
              page: 1,
              page_size: 100,
              unit_id: row.id
            });
            
            console.log('获取到的转换规则:', conversionResponse);
            
            if (conversionResponse && conversionResponse.items) {
              // API返回包含items的对象
              const matchingUnit = conversionResponse.items.find(item => item.id === row.id);
              if (matchingUnit && matchingUnit.conversions) {
                row.conversions = matchingUnit.conversions;
              } else if (Array.isArray(conversionResponse.items)) {
                // 如果items是数组但没找到匹配单位，可能items就是转换规则列表
                row.conversions = conversionResponse.items;
              }
            } else if (Array.isArray(conversionResponse)) {
              // API直接返回转换规则数组
              row.conversions = conversionResponse;
            } else {
              console.warn('未能获取到转换规则数据');
              row.conversions = [];
            }
          }
        } catch (error) {
          console.error('获取单位转换规则失败:', error);
          ElMessage.error('获取单位转换规则失败');
          row.conversions = [];
        }
      }
    }
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingUnit.value = {
    name: '',
    type: '重量单位',
    is_active: true
  }
  dialogs.unit = true
}

// 显示编辑对话框
const showEditDialog = (unit) => {
  editingUnit.value = { ...unit }
  dialogs.unit = true
}

// 提交单位表单
const handleSubmitUnit = async () => {
  try {
    await unitFormRef.value.validate()
    
    loading.submit = true
    
    if (editingUnit.value.id) {
      // 更新现有单位
      const data = {
        name: editingUnit.value.name,
        type: editingUnit.value.type,
        is_active: editingUnit.value.is_active
      }
      await updateUnitConversion(editingUnit.value.id, data)
      ElMessage.success('单位更新成功')
    } else {
      // 创建新单位
      const data = {
        name: editingUnit.value.name,
        type: editingUnit.value.type,
        is_active: editingUnit.value.is_active
      }
      await createUnitConversion(data)
      ElMessage.success('单位创建成功')
    }
    
    dialogs.unit = false
    fetchUnitList()
  } catch (error) {
    console.error('保存单位失败:', error)
    ElMessage.error('保存单位失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.submit = false
  }
}

// 删除单位
const handleDelete = async (unit) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除单位 "${unit.name}" 及其所有转换规则吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteUnitConversion(unit.id)
    ElMessage.success('单位删除成功')
    fetchUnitList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除单位失败:', error)
      ElMessage.error('删除单位失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 切换单位状态
const handleToggleStatus = async (unit) => {
  try {
    const newStatus = !unit.is_active
    const actionText = newStatus ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${actionText}单位 "${unit.name}" 吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: newStatus ? 'success' : 'warning'
      }
    )
    
    await updateUnitConversion(unit.id, { is_active: newStatus })
    ElMessage.success(`单位已${actionText}`)
    fetchUnitList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新单位状态失败:', error)
      ElMessage.error('更新单位状态失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1 // 重置到第一页
  fetchUnitList()
}

// 重置查询
const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.is_active = ''
  pagination.currentPage = 1
  fetchUnitList()
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchUnitList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUnitList()
}

// 显示批量导入对话框
const showBulkImportDialog = () => {
  bulkImportData.value = ''
  bulkImportError.value = ''
  dialogs.bulkImport = true
}

// 验证批量导入数据
const validateBulkImportData = () => {
  if (!bulkImportData.value.trim()) {
    bulkImportError.value = ''
    return
  }
  
  try {
    const data = JSON.parse(bulkImportData.value)
    if (!Array.isArray(data)) {
      bulkImportError.value = '数据格式错误，应为数组'
      return
    }
    
    for (const item of data) {
      if (!item.name) {
        bulkImportError.value = '部分数据缺少必填字段name'
        return
      }
    }
    
    bulkImportError.value = ''
  } catch (error) {
    bulkImportError.value = '无效的JSON格式: ' + error.message
  }
}

// 处理批量导入
const handleBulkImport = async () => {
  try {
    validateBulkImportData()
    if (bulkImportError.value) {
      return
    }
    
    const data = JSON.parse(bulkImportData.value)
    if (!data.length) {
      ElMessage.warning('没有数据需要导入')
      return
    }
    
    loading.bulkImport = true
    
    const response = await bulkCreateUnits({ items: data })
    ElMessage.success(`成功导入 ${response.created_count} 个单位`)
    
    if (response.error_count > 0) {
      ElMessage.warning(`${response.error_count} 个单位导入失败`)
      console.log('导入失败的单位:', response.errors)
    }
    
    dialogs.bulkImport = false
    fetchUnitList()
  } catch (error) {
    console.error('批量导入失败:', error)
    ElMessage.error('批量导入失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.bulkImport = false
  }
}

// 显示添加规则对话框
const showAddRuleDialog = (unit) => {
  currentUnit.value = unit
  editingRule.value = {
    source_unit: unit.name,
    target_unit: '',
    conversion_formula: '',
    description: '',
    is_active: true,
    page: pagination.currentPage,
    pageSize: pagination.pageSize
  }
  dialogs.rule = true
}

// 显示编辑规则对话框
const showEditRuleDialog = (unit, rule) => {
  currentUnit.value = unit
  editingRule.value = { ...rule }
  dialogs.rule = true
}

// 提交规则表单
const handleSubmitRule = async () => {
  try {
    await ruleFormRef.value.validate()
    
    loading.submitRule = true
    
    if (!currentUnit.value) {
      throw new Error('当前单位信息丢失')
    }
    
    const unitData = {
      id: currentUnit.value.id,
      name: currentUnit.value.name,
      conversions: [
        {
          id: editingRule.value.id, // 如果是编辑现有规则，会有ID
          source_unit: editingRule.value.source_unit,
          target_unit: editingRule.value.target_unit,
          conversion_formula: editingRule.value.conversion_formula,
          description: editingRule.value.description,
          is_active: editingRule.value.is_active
        }
      ]
    }
    
    await updateUnitConversion(currentUnit.value.id, unitData)
    ElMessage.success(editingRule.value.id ? '转换规则更新成功' : '转换规则添加成功')
    
    dialogs.rule = false
    fetchUnitList() // 刷新列表
  } catch (error) {
    console.error('保存转换规则失败:', error)
    ElMessage.error('保存转换规则失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.submitRule = false
  }
}

// 删除转换规则
const handleDeleteRule = async (rule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除从 "${rule.source_unit}" 到 "${rule.target_unit}" 的转换规则吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteConversionRule(rule.id)
    ElMessage.success('转换规则删除成功')
    fetchUnitList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除转换规则失败:', error)
      ElMessage.error('删除转换规则失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
}

// 计算转换公式结果（用于预览）
const evaluateFormula = (formula, value) => {
  try {
    if (!formula) return '-';
    // 将x替换为具体数值，然后计算表达式
    const calculatedFormula = formula.replace(/x/g, value);
    return eval(calculatedFormula).toFixed(2);
  } catch (error) {
    console.error('公式计算错误:', error);
    return '计算错误';
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUnits.value.length} 个单位及其所有转换规则吗？此操作不可恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    for (const unit of selectedUnits.value) {
      await deleteUnitConversion(unit.id)
    }
    ElMessage.success('选中的单位及其转换规则删除成功')
    fetchUnitList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 处理选择变化
const handleSelectionChange = (selected) => {
  selectedUnits.value = selected
}
</script>

<style scoped>
.unit-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-panel {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.bulk-import-dialog {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.format-example {
  color: #606266;
  font-size: 14px;
}

.format-example code {
  background-color: #f5f7fa;
  padding: 2px 5px;
  border-radius: 3px;
  font-family: monospace;
}

.json-error {
  margin-top: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.2;
}

.conversion-rules-container {
  padding: 10px 20px 20px 20px;
  background-color: #f9fafc;
  border-radius: 4px;
}

.rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.rules-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.conversion-rules-table {
  margin-top: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.formula-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.formula-text {
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 3px;
  color: #409eff;
  font-weight: bold;
}

.formula-example {
  padding: 5px;
}

.example-row {
  margin-bottom: 8px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 3px;
  font-family: monospace;
  color: #303133;
}

.example-row:last-child {
  margin-bottom: 0;
}
</style> 